/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.common.base.service.rpc.impl;

import com.je.common.base.DynaBean;
import com.je.common.base.constants.ConstantVars;
import com.je.common.base.db.DbFieldVo;
import com.je.common.base.db.JEDatabase;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.CommonTableRpcService;
import com.je.common.base.util.*;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RpcSchema(schemaId = "commonTableRpcService")
public class CommonTableRpcServiceImpl implements CommonTableRpcService {

    @Autowired
    private MetaService metaService;

    @Override
    public void executeSql(List<String> arraySql,String tableCode) {
        if (JEDatabase.getCurrentDatabase().equalsIgnoreCase(ConstantVars.STR_SHENTONG)
                && metaService.countBySql("select count(*) from user_cons_columns where table_name='" + tableCode + "' and column_name='SY_PARENT'") > 0) {
            arraySql.removeIf(s -> s.contains("foreign key (SY_PARENT)"));
        }
        for (String sql : arraySql) {
            sql = sql.replaceAll("\n", "");
            try {
                if (StringUtil.isNotEmpty(sql)) {
                    metaService.executeSql(sql);
                }
            } catch (Exception e) {
                String message = e.getMessage();
                if (e.getCause() != null) {
                    message = e.getCause().getMessage();
                }
                throw new PlatformException(MessageUtils.getMessage("table.update.errorInfo", sql, message), PlatformExceptionEnum.JE_CORE_TABLE_UPDATE_ERROR, new Object[]{sql}, e);
            }
        }
    }

    @Override
    public String getColumns(String sql) {
        List<DbFieldVo> fieldVos = new ArrayList<DbFieldVo>();
        Connection connection = null;
        CallableStatement proc = null;
        ResultSet resultSet = null;
        connection = metaService.getConnection();
        String fields="";
        try {
            proc = connection.prepareCall(sql);
            DbProduceUtil.registerParams(proc, fieldVos);
            proc.execute();
            resultSet = proc.getResultSet();
            ResultSetMetaData data = resultSet.getMetaData();
            int count = 0;
            count = data.getColumnCount();
            for (int i = 1; i <= count; i++) {
                String columnName = data.getColumnName(i);
                if(i==count){
                    fields+= columnName;
                }else{
                    fields+= columnName+",";
                }
            }
            return fields;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(resultSet, null,connection);
            if(proc!=null){
                try {
                    proc.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public long getDataCount(String tableCode) {
        List<Map<String,Object>> list = metaService.selectSql(ConditionsWrapper.builder()
                .apply(StringUtil.isNotEmpty(tableCode),"Select count(1) as count from "+ tableCode ));
        if(list!=null){
            return list.get(0).get("count")==null?0L:Long.parseLong(list.get(0).get("count").toString());
        }
        return 0L;
    }

    @Override
    public DynaBean getResourcetableInfoByDB(DynaBean table) {
       return DataBaseUtils.buildDynabeanTableInfo(table);
    }

    @Override
    public String checkTableExists(String tableCode) {
        return DataBaseUtils.checkTableExists(tableCode);
    }

    @Override
    public DynaBean selectOneByPk(String tableCode, String pkValue) {
        return metaService.selectOneByPk(tableCode,pkValue);
    }
}
